#/bin/bash

# Regles definitives (desactivades per què som provant-ne d'altres)

# Regles definitives (en marxa)
# Habilitem el NAT, acceptem el retorn de connexions establertes i acceptem
# les connexions SSH contra el Beyonce des de la xarxa interna
#
# 

/sbin/iptables --table nat -A POSTROUTING -o eth0 -j MASQUERADE
/sbin/iptables -A FORWARD -i eth0 -o eth1 -m state --state ESTABLISHED -j ACCEPT
/sbin/iptables -A INPUT -i eth0 -m state --state ESTABLISHED -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 22 -i eth1 -j ACCEPT
/sbin/iptables -A INPUT -p tcp --dport 80 -i eth1 -j ACCEPT
/sbin/iptables -A FORWARD -p udp --dport 53 -i eth1 -o eth0 -d 172.23.1.1 -j ACCEPT

# Importem valors de l'arxiu variables.xrx
user=`grep user_mysql /etc/xarxeta/variables.xrx`
user=${user:11}
pass=`grep pass_mysql /etc/xarxeta/variables.xrx`
pass=${pass:11}

#Deshabilitem la sortida de les MACs DENEGADES
for m in $(echo "select mac from x_denegats" | mysql -u $user -p$pass -D xarxeta | grep -v "mac")
do
	/sbin/iptables -A FORWARD -m mac --mac-source $m -i eth1 -j DROP
done


#Habilitem la sortida de les MACs autoritzades
for m in $(echo "select mac from x_actius" | mysql -u $user -p$pass -D xarxeta | grep -v "mac")
do
	/sbin/iptables -A FORWARD -m mac --mac-source $m -i eth1 -j ACCEPT
	/sbin/iptables -t nat -A PREROUTING -m mac --mac-source $m -i eth1 -d 192.168.1.1 -p tcp --dport 80 -j DNAT --to 209.85.229.147
	/sbin/iptables -t nat -A PREROUTING -m mac --mac-source $m -i eth1 -j ACCEPT
done


#Habilitem l'entrada per SSH des de les IPs de gestió externes
for m in $(echo "select ip from x_remots" | mysql -u $user -p$pass -D xarxeta | grep -v "ip")
do
	/sbin/iptables -A INPUT -s $m -p tcp --dport 22 -i eth0 -j ACCEPT
	/sbin/iptables -A INPUT -s $m -p tcp --dport 80 -i eth0 -j ACCEPT
done


#Forcem que tot el tràfic web vingui cap a la Xarxeta
#
	/sbin/iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j DNAT --to 192.168.1.1
